﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAudio.Wave;

namespace Api
{
    /// <summary>
    /// InputStream adapter
    /// </summary>
    public class Microphone
    {
        private IWaveIn line;
        private WaveFileWriter inputStream;


        public Microphone(
                float sampleRate,
                int sampleSize,
                Boolean signed,
                Boolean bigEndian) 
        {
            WaveFormat format = new WaveFormat((int)sampleRate, sampleSize, 1);
                ///, signed, bigEndian);

            try {
                if (line == null)
                {
                    CreateWaveInDevice(format);
                }
            } 
            catch (Exception e) 
            {
                throw new SystemException(e.Message);
            }
            String outputFilename = String.Format("NAudioDemo {0:yyy-MM-dd HH-mm-ss}.wav", DateTime.Now);
            inputStream = new WaveFileWriter(outputFilename, line.WaveFormat);

        }

        public void startRecording() 
        {
            line.StartRecording();
        }

        public void stopRecording() 
        {
            line.StartRecording();
        }

        public WaveFileWriter getStream()
        {
            return inputStream;
        }

        private void CreateWaveInDevice(WaveFormat format)
        {
            line = new WaveIn();
            line.WaveFormat = format;
            line.DataAvailable += OnDataAvailable;
            line.RecordingStopped += OnRecordingStopped;
        }

        void OnDataAvailable(object sender, WaveInEventArgs e)
        {
            //Debug.WriteLine("Flushing Data Available");
            inputStream.Write(e.Buffer, 0, e.BytesRecorded);
            int secondsRecorded = (int)(inputStream.Length / inputStream.WaveFormat.AverageBytesPerSecond);
        }

        void OnRecordingStopped(object sender, StoppedEventArgs e)
        {
            if (inputStream != null)
            {
                inputStream.Dispose();
                inputStream = null;
            }
        }

    }
}
